/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package clientcore;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Vector;
import clientrequest.*;
import clientresponse.ResponseFromServer;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class AndroidMain {
    private short requestCode = 0;
    private short responseCode = 0;
    private static AndroidMain androidmain = null;
    private ConnectServer cs = null;
    private DataOutputStream sendServer = null;
    private DataInputStream receiveServer = null;
    private Vector<Object> arguments = null;
    
    public AndroidMain() {
        cs = new ConnectServer(Constants.SERVER_IP,Constants.SERVER_PORT,this);
        arguments = new Vector<Object>();
        RequestToServerTable.init(this);
        ResponseFromServerTable.init(this);
    }

    public void log(String msg) {
        System.out.println(msg);
    }
    

    public void sendRequest(short requestCode) {
        sendServer = cs.getDataOutputStream();
        RequestToServer request = RequestToServerTable.get(requestCode);
        request.setOut(sendServer);
        request.send(requestCode, arguments);
        try {
            sendServer.flush();
        } catch (IOException ex) {
            Logger.getLogger(AndroidMain.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void handleResponse() {
        receiveServer = cs.getDataInputStream();
        
        
        try {
            System.out.println("1:"+receiveServer.readByte());
            System.out.println("2:"+receiveServer.readByte());
            //receiveServer.readByte();
            responseCode = (short)((receiveServer.readByte()& 0xFF)+(receiveServer.readByte()<< 8));
            System.out.println("resp code "+responseCode);
            ResponseFromServer response = ResponseFromServerTable.get(responseCode);
            response.setIn(receiveServer);
            response.process();

        }catch(IOException ex) {
            log("IO Exception in class AndroidMain in method handleResponse()"+ex.toString());
        }

    }

    public void setRequestCode(short code) {
        this.requestCode = code;
    }

    public short getRequestCode() {
        return requestCode;
    }

    public void addArguments(Object o) {
        arguments.add(o);
    }


}